package com.typingtutor.util;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class ReflectionExample {
    public static List<Object> getNonNullFieldValuesFromList(List<?> list, List<String> fieldNames) {
        List<Object> nonNullValues = new ArrayList<>();
        if (list == null || list.isEmpty() || fieldNames == null || fieldNames.isEmpty()) {
            return nonNullValues;
        }
        for (Object object : list) {
            if (object == null) {
                continue;
            }
            Class<?> clazz = object.getClass();
            for (String fieldName : fieldNames) {
                try {
                    Field field = clazz.getDeclaredField(fieldName);
                    field.setAccessible(true);
                    Object value = field.get(object);
                    if (value != null) {
                        nonNullValues.add(value);
                    }
                } catch (NoSuchFieldException | IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
        return nonNullValues;
    }

}